package com.controller.sys.user.login;

import com.common.ErrorCodeEnum;
import com.model.base.Result;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.core.sms.service.SmsServer;
import com.model.dto.sys.LoginController.GetCodeByMobileDTO;
import com.model.vo.sys.code.GetCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@Api(tags = {"公共"})
@Slf4j
@RestController
@RequestMapping("/v1")
public class SmsController {
    @Resource
    private SmsServer smsServer;

    /**
     * @Author: zql
     * @Description: 获取短信验证码服务 同一个手机号30s一次
     * @param getCodeByMobileDTO 手机号
     * @Data: 10:41 2021/5/12
     */
    @ApiOperation(value = "获取短信验证码服务")
    @Log(title = "获取短信验证码服务", businessType = BusinessType.GRANT)
    @PostMapping("/sms/getCode")
    public Result<GetCodeVO> getCode(@RequestBody @Valid GetCodeByMobileDTO getCodeByMobileDTO) {
        long countDown = smsServer.countDown(getCodeByMobileDTO.getMobile());
        GetCodeVO getCodeVO = new GetCodeVO();
        getCodeVO.setCountDown(countDown);
        if (getCodeVO.getCountDown() <= 0) {
            getCodeVO.setCountDown((long) smsServer.getInterval());
            log.info("短信验证请求，手机号:{}", getCodeByMobileDTO.getMobile());
            smsServer.senCode(getCodeByMobileDTO.getMobile());
            return Result.suc(getCodeVO);
        }
        log.warn("手机短信验证，手机号{}，距离下次发送剩余时间：{}", getCodeByMobileDTO.getMobile(), countDown);
        return Result.fail(ErrorCodeEnum.MOBILE_CODE_SEND_FAILED, getCodeVO);
    }
}
